/**
 * Created by LuckyYe on 2016/8/24.
 */

angular.module('expertsys.conversation', [])

    .config(['$stateProvider', '$urlRouterProvider',
        function ($stateProvider, $urlRouterProvider) {
            $stateProvider

                .state('conversation', {
                    url: '/conversation/:tId',
                    templateUrl: exp_templateprefix + 'home/conversation.html',
                    controller: 'ConversationController'
                })

        }])
    .controller('ConversationController', ['$scope', '$state', '$stateParams', 'ExpertsysService', 'ConversationService', 'ExpAuthService',
        function ($scope, $state, $stateParams, ExpertsysService, ConversationService, ExpAuthService) {
            var id = ExpAuthService.getUserid();
            var expert = 0;//判断有没有专家回复（0表示没有，1表示有）
            var tState = 0;//记录问题状态
            var dd = document.getElementById("con_pusImg")
            var userList = ""
            //通过topicId得到问题详细信息
            ExpertsysService.getTopicQueByTid($stateParams.tId).$promise.then(function (data) {
                //得到用户表内容
                ExpertsysService.getUserList().$promise.then(function (data_u) {
                    for (var j = 0; j < data_u.length; j++) {
                        if (data.userid == data_u[j].userid) {
                            $scope.t_uName = data_u[j].name;
                            $scope.t_userid = data_u[j].userid;
                            $scope.t_ulogo = data_u[j].logo;
                            break;
                        }
                    }
                    //把图片与文字分割
                    $scope.arrDetail = []
                    if (data.detail != null) {
                        if (data.detail.indexOf("{{img:") > 0) {
                            $scope.arrDetail = data.detail.split('{{img:')
                            for (var e = 1; e < $scope.arrDetail.length; e++) {
                                dd.innerHTML += "<li class='fatu1' style='float:left'><img id='conver_image" + e + "' src=" + $scope.arrDetail[e] + "></li>";
                            }
                        } else {
                            $scope.arrDetail.push(data.detail);
                        }
                    } else {
                        $scope.arrDetail.push(data.detail);
                    }
                    //拿到问题的内容详情
                    $scope.topicQue = {
                        'tId': $stateParams.tId,
                        'tName': data.topicname,
                        'tDetail': $scope.arrDetail[0],
                        'tCreateTime': data.createtime,
                        'tState': data.state,
                        'uName': $scope.t_uName,
                        'uLogo': $scope.t_ulogo
                    }
                    //记录问题状态
                    tState = data.state;
                    //存放user数据
                    userList = data_u;
                    //加载专家与农户的问答
                    $scope.load_conver = function (data_u) {
                        $scope.converList = [];
                        //通过tid得到专家与农户的问答
                        ConversationService.getConversationById($stateParams.tId).$promise.then(function (data_c) {
                            //得到所有专家数据
                            ExpertsysService.getExpertsysList().$promise.then(function (data_e) {
                                //把专家与提问者名字与头像信息取出
                                for (var i = 0; i < data_c.length; i++) {
                                    for (var z = 0; z < data_u.length; z++) {
                                        if (data_c[i].userid == data_u[z].userid) {
                                            $scope.c_uName = data_u[z].name;
                                            $scope.c_ulogo = data_u[z].logo;
                                            break;
                                        }
                                    }
                                    //判断留言板中留言的是专家还是提问者
                                    for (var a = 0; a < data_e.length; a++) {
                                        if (data_c[i].userid == data_e[a].userid) {
                                            $scope.expiId = data_e[a].userid;
                                            $scope.mark = 1;
                                            expert = 1;
                                            break;
                                        } else {
                                            $scope.mark = 0;
                                        }
                                    }
                                    //把问答信息push进去converList
                                    $scope.converList.push({
                                        //'userid' : data_c[i].userid,
                                        'content': data_c[i].content,
                                        'name': $scope.c_uName,
                                        'logo': $scope.c_ulogo,
                                        'time': data_c[i].lasttime,
                                        'mark': $scope.mark
                                    });
                                }
                                if (id == $scope.t_userid || id == $scope.expiId) {
                                    $scope.send_show = true;
                                } else {
                                    $scope.send_show = false;
                                }
                            });
                        });
                    }
                    $scope.load_conver(data_u);
                });
            });
            //发留言
            $scope.conversation = "";
            $scope.send = function () {
                if (id == 0) {
                    window.location.href = projectBaseUrl + "login";
                }
                else {
                    if ($(".quest-get").val() == "") {
                        input_alert("请输入要发表的评论", 2000);
                        return;
                    }
                    else if ($scope.t_userid != id && $scope.expiId != id) {
                        input_alert("不是您的问题不能回答", 2000);
                    }
                    else {
                        $scope.conversation.convid = new Date().getTime();
                        $scope.conversation.topicid = $stateParams.tId;
                        $scope.conversation.userid = id;
                        ConversationService.add_message($scope.conversation, success_func, error_func);
                    }
                }
            };
            var success_func = function () {
                input_alert("留言成功");
                $scope.conversation.content = "";
                $scope.load_conver(userList);
            }
            var error_func = function () {
                input_alert("发送失败");
            }
            //点击后退按钮触发事件
            $scope.callback = function () {
                //if(登录者是专家还是提问者){
                // 提问者
                if (expert == 1 && tState == 0) {
                    $('#myModal').modal('show');
                } else {
                    history.go(-1);
                }
                //}else{专家  history.go(-1);}
            }
            //弹窗确认按钮触发事件
            $scope.modal_sure = function () {
                //$scope.state 页面判断是选择是或否（是：1）
                if ($scope.state == 1) {
                    $scope.topicDate = {
                        'topicid': $stateParams.tId,
                        'state': 1
                    }
                    ExpertsysService.updateTopicQueByTid($scope.topicDate).$promise.then(function () {
                        $('#myModal').modal('hide');//关闭弹窗
                        tState = 1;
                    });
                } else {
                    $('#myModal').modal('hide');//关闭弹窗
                    history.go(-1);
                }
            }

        }])
;